package com.zzmm.socket.demo;

import lombok.SneakyThrows;
import org.junit.Test;

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class SocketUDPTest {

    String dir = "src/main/resources/";

    @SneakyThrows
    @Test
    public void testSocket01() {
        // 端口监听
        DatagramSocket datagramSocket = new DatagramSocket(9998);

        // 数据包
        byte[] data = "hello 明天吃火锅~".getBytes(StandardCharsets.UTF_8);
        InetAddress to = InetAddress.getByName("192.168.7.1");
        DatagramPacket datagramPacket = new DatagramPacket(data, 0, data.length, to, 9999);

        // 发送数据包
        datagramSocket.send(datagramPacket);

        // 接收回复数据包
        data = new byte[1024];
        datagramPacket.setData(data);
        datagramSocket.receive(datagramPacket);
        System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength()));

        // 关闭端口
        datagramSocket.close();
    }

    @SneakyThrows
    @Test
    public void testSocket02() {
        // 端口监听
        DatagramSocket datagramSocket = new DatagramSocket(9999);

        // 接收数据包
        byte[] data = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(data, 0, data.length);
        datagramSocket.receive(datagramPacket);

        // 读取数据
        System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength()));

        // 回复数据包
        data = "好的，明天见".getBytes(StandardCharsets.UTF_8);
        datagramPacket.setData(data);
        datagramSocket.send(datagramPacket);

        // 关闭端口
        datagramSocket.close();
    }


}
